<template>
  <div style="width: 50%;margin: 10px auto">
    <div class="card">
      <div v-if="id === '' || id === null || id === undefined" style="text-align: center;font-size: 25px;margin-bottom: 20px">
        <el-page-header @back="deleteNoImg(form.id);$router.back()" content="发布求购"></el-page-header>
      </div>
      <div v-else style="text-align: center;font-size: 25px;margin-bottom: 20px">
        <el-page-header @back="deleteNoImg(form.id);$router.back()" content="编辑求购"></el-page-header>
      </div>
      <el-form :model="form" label-width="100px" style="padding-right: 50px" :rules="rules" ref="formRef">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="标题"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input type="textarea" v-model="form.content" placeholder="内容"></el-input>
        </el-form-item>
        <el-form-item label="图片" prop="img" v-model="form.img">
          <el-upload
              :action="$baseUrl + '/files/upload'"
              :headers="{ token: user.token }"
              list-type="picture"
              :on-success="handleImgSuccess"
              :limit="1"
              :on-exceed="handleExceed"
          >
            <el-button type="primary">上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="是否解决" prop="solved" v-if="this.id !== '' && this.id !== null && this.id !== undefined">
          <el-select style="width: 100%" v-model="form.solved">
            <el-option value="未解决"></el-option>
            <el-option value="已解决"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-button type="primary" style="width: 30%;margin: 20px auto" @click="save">确认发布</el-button>
    </div>
  </div>
</template>

<script>
const imgUri =[];
import E from "wangeditor"
export default {
  name: "AddHelp",
  data() {
    return {
      id: this.$route.query.id,
      user: JSON.parse(localStorage.getItem('xm-user')),
      form: {
        solved: '未解决',
      },  // 表单数据
      rules: {  // 校验规则
        title: [
            { required: true, message: '请输入标题', trigger: 'blur' },
          ],
        content: [
            { required: true, message: '请输入内容', trigger: 'blur' },
          ],
      }
    }
  },
  created() {
    this.loadHelp()
    imgUri.push(this.getFileName(this.form.img));
  },
  methods: {
    handleExceed(files, fileList) {
      this.$message.warning('只能上传一张图片!');
    },
    loadHelp(){
      if(this.id){
        this.$request.get("/help/selectById/"+this.id).then(res => {
          this.form = res.data || {};
        })
      }
    },
    handleAdd() {   // 新增数据
      this.form = {}  // 新增数据的时候清空数据
    },
    save() {   // 保存按钮触发的逻辑  它会触发新增或者更新
      console.log(this.form)
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          console.log(imgUri)
          this.deleteImg();
          this.$request({
            url: this.form.id ? '/help/update' : '/help/add',
            method: this.form.id ? 'PUT' : 'POST',
            data: this.form
          }).then(res => {
            if (res.code === '200') {  // 表示成功保存
              this.handleAdd();  // 清空数据
              this.$message.success('发布成功')
              if(this.id === '' || this.id === null || this.id === undefined) {
                this.$router.push("/front/home")
              }
              else{
                this.$router.push("/front/userHelp")
              }
            } else {
              this.$message.error(res.msg)  // 弹出错误的信息
            }
          })
        }
      })
    },
    handleImgSuccess(response, file, fileList) {
      this.form.img = response.data
      let fileName = response.data.substring(response.data.lastIndexOf('/') + 1)
      imgUri.push(fileName)
      console.log(imgUri)
    },
    deleteImg(){
      console.log(imgUri)
      if(imgUri.length > 1) {
        imgUri.pop();
        console.log(imgUri)
        this.$request.delete('/files/delete/batch', {data: imgUri})
      }
      //   清空imgUri
      imgUri.length = 0
    },
    deleteNoImg(id){
      if(id !== void 0){
        imgUri.splice(0, 1);
      }
      console.log(imgUri)
      this.$request.delete('/files/delete/batch', {data: imgUri})
      //   清空imgUri
      imgUri.length = 0
    },
    getFileName(filePath){
      return filePath?.substring(filePath.lastIndexOf('/') + 1)
    }
  }
}
</script>

<style scoped>
.card {
  /* 背景颜色 */
  background-color: #fff;

  /* 边框样式 */
  border: 1px solid #e0e0e0;

  /* 圆角 */
  border-radius: 8px;

  /* 盒子阴影效果 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  /* 内边距 */
  padding: 20px;

  /* 外边距 */
  margin: 20px 0;

  /* 宽度设置，可以根据实际情况调整 */
  width: 100%;
  max-width: 800px;

  /* 确保内容垂直居中 */
  display: flex;
  flex-direction: column;
  justify-content: center;
}
</style>